import { AvatarDropdown, AvatarName, Footer } from '@/components';
import ServerImageUpload from '@/components/Element/ServerImageUpload';
import ServerImageUploadFold from '@/components/Element/ServerImageUploadFold';
import { ThemeProvider } from '@/contexts/ThemeContext';
import type { ThemeConfig } from '@/types/theme';
import { BellOutlined } from '@ant-design/icons';
import {
  ProConfigProvider,
  ProFormText,
  ProRenderFieldPropsType,
  type Settings as LayoutSettings,
} from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { Badge, ConfigProvider, message } from 'antd';
import React, { useCallback, useEffect, useState } from 'react';
import { RequestConfig } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { STATIC_PATHS } from '../config/paths';
import LoginUtil from './utils/loginUtil';

// 定义当前用户类型
type CurrentUser = {
  name: string;
  avatar?: string;
  userid?: string;
  email?: string;
  signature?: string;
  title?: string;
  group?: string;
  tags?: {
    key: string;
    label: string;
  }[];
  notifyCount?: number;
  unreadCount?: number;
  country?: string;
  access?: string;
  geographic?: {
    province: {
      label: string;
      key: string;
    };
    city: {
      label: string;
      key: string;
    };
  };
  address?: string;
  phone?: string;
};

// 全局抑制 findDOMNode 警告
const originalError = console.error;
console.error = (...args) => {
  if (args[0] && typeof args[0] === 'string' && args[0].includes('findDOMNode')) {
    return;
  }
  originalError.apply(console, args);
};

const loginPath = '/user/login';

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<CurrentUser | undefined>;
}> {
  // 由于 /api/currentUser 接口不存在，直接返回空用户信息
  const fetchUserInfo = async (): Promise<CurrentUser | undefined> => {
    try {
      // 从 localStorage 读取 admin 信息作为用户信息
      const adminData = localStorage.getItem('admin');
      if (adminData) {
        try {
          const admin = JSON.parse(adminData);
          return {
            name: admin.username || 'Admin',
            avatar: admin.avatar || undefined,
            userid: admin.id || admin.userId || undefined,
            access: 'admin',
          } as CurrentUser;
        } catch (e) {
          console.warn('解析admin数据失败:', e);
          return {
            name: adminData,
            access: 'admin',
          } as CurrentUser;
        }
      }
      return undefined;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      return undefined;
    }
  };

  // 检查是否有登录token
  const token = localStorage.getItem('token');

  // 如果不是登录页面，且有token，从localStorage获取用户信息
  const { location } = history;
  if (location.pathname !== loginPath && token) {
    try {
      const currentUser = await fetchUserInfo();
      return {
        fetchUserInfo,
        currentUser,
        settings: defaultSettings as Partial<LayoutSettings>,
        loading: false,
      };
    } catch (error) {
      console.error('初始化用户状态失败:', error);
      // 如果获取用户信息失败，清除token并重定向到登录页
      localStorage.removeItem('token');
      localStorage.removeItem('admin');
      history.push(loginPath);
      return {
        fetchUserInfo,
        settings: defaultSettings as Partial<LayoutSettings>,
        loading: false,
      };
    }
  }

  // 如果没有token且不是登录页面，跳转到登录页
  if (!token && location.pathname !== loginPath) {
    history.push(loginPath);
  }

  return {
    fetchUserInfo,
    settings: defaultSettings as Partial<LayoutSettings>,
    loading: false,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    actionsRender: () => [],
    avatarProps: {
      src: initialState?.currentUser?.avatar,
      title: <AvatarName />,
      render: (_, avatarChildren) => {
        return (
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              width: '100%',
              paddingRight: '20px',
            }}
          >
            <AvatarDropdown>{avatarChildren}</AvatarDropdown>
            <Badge count={0}>
              <BellOutlined style={{ width: 20, height: 20, fontSize: 18, color: 'white' }} />
            </Badge>
          </div>
        );
      },
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 只在非登录页面检查登录状态，避免无限重定向
      if (location.pathname !== loginPath && !localStorage.getItem('token')) {
        history.push(loginPath);
      }
    },
    // 添加配置来减少警告
    suppressSiderWhenMenuEmpty: true,
    ...initialState?.settings,
  };
};

/**
 * @name request 配置，可以配置错误处理
 * 它基于 axios 和 ahooks 的 useRequest 提供了一套统一的网络请求和错误处理方案。
 * @doc https://umijs.org/docs/max/request#配置
 */
// 错误处理方案： 错误类型
enum ErrorShowType {
  SILENT = 0,
  WARN_MESSAGE = 1,
  ERROR_MESSAGE = 2,
  NOTIFICATION = 3,
  REDIRECT = 9,
}

// 与后端约定的响应数据格式
interface ResponseStructure {
  code: number;
  data: any;
  errorCode?: number;
  errorMessage?: string;
  showType?: ErrorShowType;
}

// App 组件定义
const App = (props: any) => {
  // 只保留默认主题
  const [theme, setTheme] = useState<ThemeConfig>({
    layout: defaultSettings as any,
    user: {
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    },
    welcome: {
      bg: STATIC_PATHS.images.bg,
    },
    login: {
      bg: STATIC_PATHS.images.bg,
    },
    footer: {
      copyright: '2025 测试有限公司出品',
    },
  });

  const initThemeConfig = useCallback(async () => {
    try {
      const customerSetting = await LoginUtil.getThemeConfig();
      document.title = customerSetting.layout?.title || '管理后台';
      // 修改全局css变量
      document.documentElement.style.setProperty(
        '--color-primary',
        customerSetting?.layout?.colorPrimary || '',
      );
      setTheme(customerSetting);
    } catch (error) {
      console.log('error2', error);
      // 无法获取配置信息,并且非登录页面 传送到404
      history.push('/404');
    }
  }, []);

  useEffect(() => {
    initThemeConfig();
  }, []);

  useEffect(() => {
    const { hash } = window.location;
    if (hash) {
      const element = document.querySelector(hash);
      if (element) {
        element.scrollIntoView();
      }
    }
  }, [location.pathname]);

  useEffect(() => {
    const { hash } = window.location;
    if (hash) {
      const element = document.querySelector(hash);
      if (element) {
        element.scrollIntoView();
      }
    }
  }, [location.pathname]);

  const valueTypeMap: Record<string, ProRenderFieldPropsType> = {
    // 上传图片 - 改为服务器上传
    upload: {
      renderFormItem: (text, props) => {
        const fieldProps = props.fieldProps;
        return (
          <ServerImageUpload
            uploadType={fieldProps.upload_type}
            {...fieldProps}
          ></ServerImageUpload>
        );
      },

      // 只读模式 对应dataIndex有值才会渲染
      render: (text, props) => {
        const fieldProps = props.fieldProps || {};
        return <ServerImageUpload readonly={true} {...fieldProps}></ServerImageUpload>;
      },
    },
    uploadFold: {
      renderFormItem: (text, props) => {
        const fieldProps = props.fieldProps;
        return (
          <ServerImageUploadFold
            uploadType={fieldProps.upload_type}
            {...fieldProps}
          ></ServerImageUploadFold>
        );
      },

      // 只读模式 对应dataIndex有值才会渲染
      render: (text, props) => {
        const fieldProps = props.fieldProps || {};
        return <ServerImageUploadFold readonly={true} {...fieldProps}></ServerImageUploadFold>;
      },
    },
    hidden: {
      renderFormItem: (text, props) => {
        const fieldProps = props.fieldProps;
        return <ProFormText name={fieldProps.dataIndex} hidden />;
      },
    },
  };

  const colorPrimary = theme?.layout?.colorPrimary || defaultSettings.colorPrimary;

  return (
    <ThemeProvider theme={theme}>
      <ConfigProvider
        theme={{
          token: {
            colorPrimary: colorPrimary,
          },
        }}
      >
        <ProConfigProvider valueTypeMap={valueTypeMap}>{props.children}</ProConfigProvider>
      </ConfigProvider>
    </ThemeProvider>
  );
};

export function rootContainer(container: any) {
  return <App>{React.cloneElement(container, container.props, container.props.children)}</App>;
}

// 请求拦截器：添加认证头
const authHeaderInterceptor = (url: string, options: any) => {
  const token = localStorage.getItem('token');

  // 如果没有token，直接返回原始配置
  if (!token) {
    return { url, options };
  }

  // 创建请求头对象
  const authHeader = {
    Authorization: `Bearer ${token}`,
  };

  // 返回更新后的 URL 和选项
  return {
    url,
    options: {
      ...options,
      headers: {
        ...options.headers,
        ...authHeader,
      },
    },
  };
};

// 响应拦截器：处理响应数据
const responseInterceptor = (response: any) => {
  try {
    const { data } = response;

    // 处理版本更新
    if (data.code === 432) {
      message.error('检测到版本更新，请重新登录');
      // 清除本地存储
      localStorage.removeItem('token');
      localStorage.removeItem('admin');
      // 强制刷新到登录页
      window.location.href = `${window.location.protocol}//${
        window.location.host
      }${loginPath}?_=${new Date().getTime()}`;
      return response;
    }

    // 处理业务错误
    if (data.code !== 200 && data.msg) {
      message.error(data.msg);
    }

    // 处理未授权错误
    if (data.code === 401) {
      message.error('登录已过期，请重新登录');
      localStorage.removeItem('token');
      localStorage.removeItem('admin');
      history.push(loginPath);
    }

    return response;
  } catch (error) {
    console.error('响应拦截器处理失败:', error);
    return response;
  }
};

export const request: RequestConfig = {
  timeout: 1000 * 90,
  headers: { 'X-Requested-With': 'XMLHttpRequest' },

  errorConfig: {
    errorThrower: (res: ResponseStructure) => {
      const { code, data, errorCode, errorMessage, showType } = res;
      if (code !== 1) {
        const error: any = new Error(errorMessage);
        error.name = 'BizError';
        error.info = { errorCode, errorMessage, showType, data };
        throw error;
      }
    },
    errorHandler: (error: any, opts: any) => {
      if (opts?.skipErrorHandler) throw error;
      if (error.name === 'BizError') {
        const errorInfo: ResponseStructure | undefined = error.info;
        if (errorInfo) {
          const { errorMessage } = errorInfo;
          switch (errorInfo.showType) {
            case ErrorShowType.SILENT:
              break;
            case ErrorShowType.WARN_MESSAGE:
              console.log('errorMessage==', errorMessage);
              break;
            case ErrorShowType.ERROR_MESSAGE:
              console.log('errorMessage==', errorMessage);
              break;
            case ErrorShowType.NOTIFICATION:
              console.log('errorMessage==', errorMessage);
              break;
            case ErrorShowType.REDIRECT:
              break;
            default:
              console.log('errorMessage==', errorMessage);
          }
        }
      } else if (error.response) {
        console.log('请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围');
        if (error.response.data.code === 401) {
          message.error('登录已过期，请重新登录');
          localStorage.removeItem('token');
          localStorage.removeItem('admin');
          history.push(loginPath);
        }
      } else if (error.request) {
        console.log('请求已经成功发起，但没有收到响应');
      } else {
        console.log('发送请求时出了点问题');
      }
    },
  },

  // 请求拦截器
  requestInterceptors: [authHeaderInterceptor],

  // 响应拦截器
  responseInterceptors: [responseInterceptor],
};
